package com.jinzhi.jzweb.service.moduleConfig.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.dao.moduleConfig.JzJinzhuanDispositionModuleMapper;
import com.jinzhi.jzweb.domain.ExaminationBatchComDO;
import com.jinzhi.jzweb.domain.ExaminationBatchComSDO;
import com.jinzhi.jzweb.domain.MarkDO;
import com.jinzhi.jzweb.domain.MarkVO;
import com.jinzhi.jzweb.pojo.ModuleConfig.*;
import com.jinzhi.jzweb.service.ExaminationBatchComSService;
import com.jinzhi.jzweb.service.ExaminationBatchComService;
import com.jinzhi.jzweb.service.MarkService;
import com.jinzhi.jzweb.service.moduleConfig.IJzJinzhuanDispositionModuleService;
import com.jinzhi.jzweb.service.moduleConfig.IJzJinzhuanDispositionTopicService;
import com.jinzhi.jzweb.service.moduleConfig.JzJinzhuanModuleContentService;
import com.jinzhi.jzweb.service.moduleConfig.JzJinzhuanModuleDetailService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

import static cn.afterturn.easypoi.excel.entity.enmus.CellValueType.String;

/**
 * <p>
 *  模版服务实现类
 * </p>
 *
 * @author JingChangTian
 * @since 2023-06-16
 */
@Service
public class JzJinzhuanDispositionModuleServiceImpl extends ServiceImpl<JzJinzhuanDispositionModuleMapper, JzJinzhuanDispositionModule> implements IJzJinzhuanDispositionModuleService {

    private final IJzJinzhuanDispositionTopicService dispositionTopicService;

    private final UserService userService;

    @Autowired
    private MarkService markService;

    @Autowired
    private JzJinzhuanModuleDetailService jzJinzhuanModuleDetailService;

    @Autowired
    private ExaminationBatchComSService examinationBatchComSService;


    @Autowired
    private JzJinzhuanModuleContentService jzJinzhuanModuleContentService;


    private final JzJinzhuanDispositionModuleMapper moduleMapper;

    private final ExaminationBatchComService examinationBatchComService;

    public JzJinzhuanDispositionModuleServiceImpl(IJzJinzhuanDispositionTopicService dispositionTopicService,
                                                  UserService userService, JzJinzhuanDispositionModuleMapper moduleMapper,
                                                  ExaminationBatchComService examinationBatchComService) {
        this.dispositionTopicService = dispositionTopicService;
        this.userService = userService;
        this.moduleMapper = moduleMapper;
        this.examinationBatchComService = examinationBatchComService;
    }

    @Override
    public boolean insertModule(JzJinzhuanDispositionModule jzJinzhuanDispositionModule){
        boolean sm = insert(jzJinzhuanDispositionModule);//存入模板数据
        jzJinzhuanDispositionModule.setDispositionTopic(Optional.ofNullable(jzJinzhuanDispositionModule.getDispositionTopic()).orElse(new ArrayList<JzJinzhuanDispositionTopic>()));
        jzJinzhuanDispositionModule.getDispositionTopic().forEach(JzJinzhuanDispositionTopic -> {
            JzJinzhuanDispositionTopic.setModuleId(jzJinzhuanDispositionModule.getId());//将模板id存入
            dispositionTopicService.insert(JzJinzhuanDispositionTopic);//存入模板任务数据（存入裁判id数据）
        });
        return sm;
    }

    @Override
    public List<JzJinzhuanDispositionModule> getModuleList(JzJinzhuanDispositionModule module){
        Wrapper wrapper = new EntityWrapper().like(StringUtils.isNotEmpty(module.getModuleName()),"module_name", module.getModuleName()).
                eq(Objects.nonNull(module.getId()),"id",module.getId()).
                eq("is_deleted",0).
                eq(Objects.nonNull(module.getModuleType()),"module_type",module.getModuleType()).
                andNew(StringUtil.notEmpty(module.getCompetitionType()),"{0} like CONCAT('%',competition_type,'%')",module.getCompetitionType()).
                eq(StringUtil.notEmpty(module.getCompetitionType()),"competition_type",module.getCompetitionType()).
                orderBy("creater_date",true);
        if (Objects.nonNull(module.getCreaterId())){
            wrapper.eq("creater_id",module.getCreaterId());
        }
        List<JzJinzhuanDispositionModule> dispositionModules = selectList(wrapper);
        //获取模块下所有的任务
        List<Long> moduleIds = dispositionModules.stream().map(JzJinzhuanDispositionModule::getId).distinct().collect(Collectors.toList());
        List<JzJinzhuanDispositionTopic> dispositionTopics = dispositionTopicService.selectList(new EntityWrapper<JzJinzhuanDispositionTopic>().in("module_id",moduleIds));
        //任务集合是否为空
        if(ObjectUtils.isEmpty(dispositionTopics)){
            return dispositionModules;
        }
        dispositionModules.forEach(a -> dispositionTopics.forEach(b ->{
            a.setDispositionTopic(Optional.ofNullable(a.getDispositionTopic()).orElse(new ArrayList<JzJinzhuanDispositionTopic>()));
            if(Objects.equals(a.getId(),b.getModuleId())){
                a.getDispositionTopic().add(b);
            }
            /*//获取创建人
            UserDO userDO = Optional.ofNullable(userService.selectById(a.getCreaterId())).orElse(new UserDO());
            a.setCreaterName(userDO.getUsername());*/
        }));
        return dispositionModules;
    }

    @Override
    public Page<JzJinzhuanDispositionModule> getPageModuleList(JzJinzhuanDispositionModule module){
        Page<JzJinzhuanDispositionModule> page = new Page<>(
                Optional.ofNullable(module.getCurrent()).orElse(1),
                Optional.ofNullable(module.getSize()).orElse(10));
        Wrapper wrapper = new EntityWrapper().like(StringUtils.isNotEmpty(module.getModuleName()),"module_name",module.getModuleName()).
                eq("is_deleted",0).
                eq(Objects.nonNull(module.getModuleType()),"module_type",module.getModuleType()).
                eq(Objects.nonNull(module.getId()),"id",module.getId()).
                andNew(StringUtil.notEmpty(module.getCompetitionType()),"{0} like CONCAT('%',competition_type,'%')",module.getCompetitionType()).
                orderBy("creater_date",true);
        if (Objects.nonNull(module.getCreaterId())){
            wrapper.eq("creater_id",module.getCreaterId());
        }
        Page<JzJinzhuanDispositionModule> dispositionModules = selectPage(page,wrapper);
        //获取模块下所有的任务
        List<Long> moduleIds = dispositionModules.getRecords().stream().map(JzJinzhuanDispositionModule::getId).distinct().collect(Collectors.toList());
        List<JzJinzhuanDispositionTopic> dispositionTopics = dispositionTopicService.selectList(new EntityWrapper<JzJinzhuanDispositionTopic>().in("module_id",moduleIds));
        //任务集合是否为空
        if(ObjectUtils.isEmpty(dispositionTopics)){
            return dispositionModules;
        }
        dispositionModules.getRecords().forEach(a -> dispositionTopics.forEach(b ->{
            a.setDispositionTopic(Optional.ofNullable(a.getDispositionTopic()).orElse(new ArrayList<JzJinzhuanDispositionTopic>()));
            if(Objects.equals(a.getId(),b.getModuleId())){
                a.getDispositionTopic().add(b);
            }
           /* //获取创建人
            UserDO userDO = Optional.ofNullable(userService.selectById(a.getCreaterId())).orElse(new UserDO());
            a.setCreaterName(userDO.getUsername());*/
        }));
        return dispositionModules;
    }

    @Override
    @Transactional
    public boolean deleteModuleById(List<Long> ids){
        //删除模块下任务
        ids.forEach(a ->{
            dispositionTopicService.delete(new EntityWrapper<JzJinzhuanDispositionTopic>().eq("module_id",a));
        });
        //删除模块
        return deleteBatchIds(ids);
    }

    @Override
    @Transactional
    public boolean updateModuleById(JzJinzhuanDispositionModule jzJinzhuanDispositionModule){
         //删除模块下任务
         Optional.ofNullable(jzJinzhuanDispositionModule)
                .map(JzJinzhuanDispositionModule::getId)
                .orElseThrow(() -> new RuntimeException("根据id修改没有id"));
                //根据module_id删除数据库中对应的模板任务
//        dispositionTopicService.delete(new EntityWrapper<JzJinzhuanDispositionTopic>().eq("module_id",jzJinzhuanDispositionModule.getId()));
        ///修改所属任务
        ArrayList<Long>	ids	=	new ArrayList<>();
        String refereeId = "";
        Long modelId = null;
        for (int i = 0;i < jzJinzhuanDispositionModule.getDispositionTopic().size();i++){
            //拿出裁判所有id
            refereeId = jzJinzhuanDispositionModule.getDispositionTopic().get(i).getRefereeId() + ","+ refereeId;
            modelId  = jzJinzhuanDispositionModule.getDispositionTopic().get(i).getModuleId();
            dispositionTopicService.insertOrUpdate(jzJinzhuanDispositionModule.getDispositionTopic().get(i));
        }
        //修改模板后跟新对应赛场的裁判数据
        EntityWrapper<ExaminationBatchComSDO> wrapper =new EntityWrapper();
        wrapper.eq("modile_id",modelId);
        List<Long> ebatchIds = examinationBatchComSService.selectList(wrapper).stream().map(ExaminationBatchComSDO::getPId).collect(Collectors.toList());
        if (ebatchIds.size() > 0){
            List<ExaminationBatchComDO> examinationBatchComDOS = examinationBatchComService.selectBatchIds(ebatchIds);
            for (int i = 0;i<examinationBatchComDOS.size();i++){
                ExaminationBatchComDO examinationBatchComDO = examinationBatchComDOS.get(i);
                examinationBatchComDO.setRefereeId(refereeId);
            }
            examinationBatchComService.updateBatchById(examinationBatchComDOS);
        }
        //修改模块信息
        return updateById(jzJinzhuanDispositionModule);
    }


    @Override
    public Result selectModule(ModuleTopicMarkVo moduleTopicMarkVo){
        //根据子赛场父级id查询父级关联裁判信息
//        ExaminationBatchComDO examinationBatchComDO = examinationBatchComService.selectById(moduleTopicMarkVo.getPid());
//        if(Objects.isNull(examinationBatchComDO.getRefereeB())&&Objects.isNull(examinationBatchComDO.getRefereeC())){
//            //如果没有绑定裁判
//           return Result.build(300,"赛场没有绑定裁判");
//        }
//        //裁判所属赛场判断(B或C)，如果B,C都能匹配上那么这个裁判既属于B赛道也属于C赛道
//        if(Objects.nonNull(examinationBatchComDO.getRefereeB())){
//            if(examinationBatchComDO.getRefereeB().contains(moduleTopicMarkVo.getUserId())){//如果裁判id与赛场表中配置的id能匹配上说明是B赛道裁判
//                moduleTopicMarkVo.setType("B");
//            }
//        }
//        if(Objects.nonNull(examinationBatchComDO.getRefereeC())){
//            if(examinationBatchComDO.getRefereeC().contains(moduleTopicMarkVo.getUserId())){
//                moduleTopicMarkVo.setType("C");
//            }
//        }
        //备注查询
        EntityWrapper wrapper =new EntityWrapper();
        wrapper.eq("sign_id",moduleTopicMarkVo.getSignId());
        wrapper.eq("race_id",moduleTopicMarkVo.getRaceId());
        wrapper.eq("referee_id",moduleTopicMarkVo.getRefereeId());
        //查询一下是否是超级管理员
        UserDO userDO = new UserDO();
        userDO.setId(moduleTopicMarkVo.getRefereeId());
        UserDO user = userService.selectOne(userDO);
        if (user.getUsername().equals("超级管理员") || user.getUsername().equals("汤武宁")){
            moduleTopicMarkVo.setRefereeId(null);
        }
        //查询对应的模板（模板中的任务有B任务和C任务，根据上面的赛道判断，查询出对应的B或C模板任务）moduleTopicMarkVo = {ModuleTopicMarkVo@13458} "ModuleTopicMarkVo(moduleId=84, topicId=null, moduleName=null, topicName=null, updateScore=null, score=null, topicScore=null, video=null, picture=null, ebatchId=null, signId=1678669729134333956, refereeId=1650432471143059458, markId=null, raceId=1678673058052755457, description=null, type=null, userId=1650432471143059458, pid=1678669299381751810, totalScore=null, jinzhuanTopicId=null, detailId=null, detailContent=null)"
        List<ModuleTopicMarkVo> list = moduleMapper.selectModule(moduleTopicMarkVo);
        //查询出对应的裁判打分数据（现在是打的总分了，因此这里返回裁判的数据就只有一条，就是这个裁判打的分数）
        List<MarkDO> MarkList = markService.selectList(wrapper);
        //查询出批次
        ExaminationBatchComDO examinationBatchComDO = new ExaminationBatchComDO();
        examinationBatchComDO.setId(moduleTopicMarkVo.getCbatchId());
        EntityWrapper batchwrapper =new EntityWrapper();
        batchwrapper.eq("cbatch_id",moduleTopicMarkVo.getCbatchId());
        ExaminationBatchComDO examinationBatchCom = examinationBatchComService.selectOne(batchwrapper);
        ModuleTopicMarkScoreVo moduleTopicMarkScoreVo = new ModuleTopicMarkScoreVo();
        //对应的模板任务细则
        for (int i = 0;i<list.size();i++){
            EntityWrapper<JzJinzhuanModuleContent> JzJinzhuanModuleContentEntityWrapper = new EntityWrapper<>();
            JzJinzhuanModuleContentEntityWrapper.eq("module_content_id",list.get(i).getDetailId());
            //对应任务模板的细则数据
            List<JzJinzhuanModuleContent> jzJinzhuanModuleContents = jzJinzhuanModuleContentService.selectList(JzJinzhuanModuleContentEntityWrapper);
            //将细则存入对象
            list.get(i).setJzJinzhuanModuleContent(jzJinzhuanModuleContents);
            for (int k = 0;k<jzJinzhuanModuleContents.size();k++){
                if (list.get(i).getDetailId().equals(jzJinzhuanModuleContents.get(k).getModuleContentId())){
                      list.get(i).setDetailContent(jzJinzhuanModuleContents.get(k).getContentName());
                }
                list.get(i).setMarkStatus(0);
                //这里查询出对应的裁判打分数据,然后再在后面拼接(将裁判已打过的细则的数据拼到对应的细则对象中去)
//               for (int e = 0; e < MarkList.size();e++){//循环查询出来的裁判的的细则分数据
//                        //1.模板id要相同 2.细则id相同 （因为上面是查询出了对应学员的打分数据，所以下面判断的时候只需要这几个参数相同即可）
//                        if (Long.valueOf(MarkList.get(e).getContentId()).equals(jzJinzhuanModuleContents.get(k).getId())){
//                            System.out.println("进入赋值");
//                            jzJinzhuanModuleContents.get(k).setUpdateScore(MarkList.get(e).getUpdateScore());
//                            jzJinzhuanModuleContents.get(k).setScore(MarkList.get(e).getUpdateScore());
//                            jzJinzhuanModuleContents.get(k).setVideo(MarkList.get(e).getVideo());
//                            jzJinzhuanModuleContents.get(k).setPicture(MarkList.get(e).getPicture());
//                            jzJinzhuanModuleContents.get(k).setEbatchId(MarkList.get(e).getEbatchId());
//                            jzJinzhuanModuleContents.get(k).setSignId(MarkList.get(e).getSignId());
//                            jzJinzhuanModuleContents.get(k).setRefereeId(MarkList.get(e).getRefereeId());
//                            jzJinzhuanModuleContents.get(k).setMarkId(MarkList.get(e).getId());
//                            jzJinzhuanModuleContents.get(k).setCbatchId(MarkList.get(e).getCbatchId());
//                            jzJinzhuanModuleContents.get(k).setRaceId(MarkList.get(e).getRaceId());
//                            //将视频和图片放到上一层去
//                            list.get(i).setVideo(MarkList.get(e).getVideo());
//                            list.get(i).setPicture(MarkList.get(e).getPicture());
//                            list.get(i).setMarkStatus(0);
//                        }
//               }
            }
            list.get(i).setBatchName(examinationBatchCom.getName());
        }
        if(list != null && list.size() > 0){
            moduleTopicMarkScoreVo.setModuleTopicMarkVo(list);
            moduleTopicMarkScoreVo.setTotalScore(list.get(0).getTotalScore());//总分
        }
        //备注回显(和裁判打分的回显)
        if (MarkList != null && MarkList.size() > 0){
           for (int i = 0;i < MarkList.size();i++){
               if (MarkList.get(i).getRefereeRemark() != null && !MarkList.get(i).getRefereeRemark().equals("")){
                   moduleTopicMarkScoreVo.setRefereeRemark(MarkList.get(i).getRefereeRemark());//备注
               }
               moduleTopicMarkScoreVo.setRefereeScore(MarkList.get(i).getUpdateScore());//裁判打的分
           }
        }
        return Result.ok(moduleTopicMarkScoreVo);
//       return Result.ok(moduleMapper.selectModule(moduleTopicMarkVo));
    }

    @Override
    public List<JzJinzhuanModuleDetail> selectModuleDetail(Map map) {
        //任务模板信息
        List<JzJinzhuanModuleDetail> jzJinzhuanModuleDetails = moduleMapper.selectModuleDetail(map);
        return jzJinzhuanModuleDetails;
    }


}
